<template>
  <div class="bcRhide">
    <!-- 列表显示 begin  -->
    <div v-show="isSimpleSearch">
      <div class="xzsourTop">
        <span class="xzname">请选择资源库：</span>
        <select name="相关度" class="cnkiselectA" v-model="simpleResType">
          <option :value="data.key" v-for="data in cnkiTypeList">{{data.name}}</option>
        </select>
      </div>
      <!--简单检索-->
      <div class="simpSeaBox">
        <div class="bcRcon_top">
          <i :class="{cur:cnkiType==item.key}" v-for="item in tabConfig" @click="cnkiType=item.key">{{item.name}} </i>
          <div class="cnkimore" v-if="false">
            <span class="cnkgd">更多</span>
            <div class="cnkimoreHide">
              <ins class="ytjj"></ins>
              <span>教学教案</span>
              <span>多媒体教辅</span>
              <span>理化生实验室</span>
              <span>期刊（完中版）</span>
              <span>期刊（高中版）</span>
              <span>期刊（初中版）</span>
              <span>期刊（小学版）</span>
            </div>
          </div>
        </div>
        <!--  简单检索 begin -->
        <div class="ordSeaBox  clearfix">
          <ul class="cnSeaLi cnSeaLiB">
            <li class="cnkiS01">
              <select name="" class="cnkiselectA" v-model="cnkiTheme">
                <option :value="item.key" v-for="item in searchConfig">{{item.name}}</option>
              </select>
            </li>
            <li class="cnkiS02">
              <input type="text" placeholder="输入检索词" class="cnkipitA" v-model.trim="cnkikey"
                     @keyup.enter="cnkiDataRetrieve(1)">
              <input type="button" value="搜索" class="bcseabtn fl" @click="cnkiDataRetrieve(1)">
            </li>
            <li class="cnkiS03" @click="advanceSearch">
              <a class="advSeabtn" title="高级检索">高级检索</a>
            </li>
          </ul>
        </div>
        <!--  简单检索 end -->
        <div class="cnkiSort">
                    <span class="fl" v-if="isAddBtn&&simpleResType!='Picture'&&simpleData.length>0">
                        <ins :class="{mcheck:simpleAlChecked,mchecked:!simpleAlChecked}"
                             @click="cnkiDataAllCheckFn(simpleData,'simple')"></ins>全选
                    </span>
          <span class="tjbtn fl" style="margin-left: 10px;" @click="returnCnkiData(simpleData)"
                v-if="isAddBtn&&simpleResType!='Picture'&&simpleData.length>0">+ {{addBtnName}}
                    </span>
          <span class="fr cnkitotal">共
                        <em class="orange">{{simpleTotal}}</em>条
                    </span>
          <div class="xbSort fr" v-if="simpleResType!='CFED1'&&simpleResType!='Picture'"> 排序：
            <span v-bind:class="{activeB:cnkiSorting==item.key}"
                  v-for="item in sortConfig"
                  @click="cnkiSorting=item.key"> {{item.name}}</span>
          </div>
        </div>
        <div class="cnkibox">
          <div>
            <!-- line -->
            <dl class="cnkiList" v-for="data,index in simpleData">
              <dt class="blue">
                                <span class="checkbtn" v-if="isAddBtn&&simpleResType!='Picture'">
                                    <ins :class="{mcheck:data.isChecked,mchecked:!data.isChecked}"
                                         @click="cnkiDataCheckFn(data,simpleData,'simple')"></ins>
                                </span>
                <p v-html="(simplePageIndex-1)*simplePageSize+index+1+'.'+data.Title"
                   @click="toggleSummary(data,simpleData)"></p>
              </dt>
              <dd class="author">
                <p class="cnkitop">
                  <span class="cnkiauthor" v-html="data.Creator"> </span>
                  <span class="journal" v-html="data.Contributor"></span>
                  <span class="nianqi" v-html="data.Year"></span>
                  <span class="gray" v-html="data.Source"></span>
                </p>
              </dd>
              <dd class="cnkiSumary" v-show="data.SummaryShow">
                <p class="cnkitext" v-html="data.Summary"></p>
                <p class="sumbot">
                  <span class="fbdate fl"> 发表时间：{{data.Year}}</span>
                  <span class="fr">
                                        <a class="cnkiread" @click="readFullText(simpleResType,data,true)">阅读</a>
                                        <a class="cnkizwj" :href="data.LinkHref" target="_blank" v-if="simpleResType!=='Picture'"> 知网节</a>
                                    </span>
                </p>
              </dd>
            </dl>
          </div>
          <!-- 控制大空间和小空间的分页样式-->
          <div v-show="simpleTotal>simplePageSize&&!isSimpleLoading" class="el-page-con">
            <el-pagination @current-change="simplePageHandle"
                           :current-page.sync="simplePageIndex"
                           :page-size="simplePageSize"
                           :pager-count="5"
                           layout=" pager, jumper"
                           :total="simpleTotal">
            </el-pagination>
          </div>
          <!-- 没有搜索时显示  begin -->
          <div class="cnkinodata" v-if="initFlag">
            <b class="orange">提示：</b>
            <p>您可以参阅本校师生编创的教案、课件、作品等教学成果；</p>
            <p>也可将成果添加到您的资料中，用于教学或研究。</p>
          </div>
          <div class="cnkinodata" v-if="isSimpleLoading">
            <p>正在检索请稍后.....</p>
          </div>
          <div class="cnkinodata" v-if="isSimpleNull">
            <b class="orange">提示：</b>
            <p>没有符合条件的资源!</p>
          </div>
          <!-- 没有搜索时显示  end -->
          <!-- line end -->
        </div>
      </div>
    </div>
    <!-- 列表显示 end  -->
    <!-- 复杂检索 begin -->
    <div v-show="isAdvanceSearch">
      <div class="xzsourTop">
        <span class="xzname">请选择资源库：</span>
        <select name="相关度" class="cnkiselectA" v-model="advanceResType">
          <option :value="data.key" v-for="data in cnkiTypeList">{{data.name}}</option>
        </select>
      </div>
      <!--简单检索-->
      <div class="simpSeaBox">
        <!--  复杂检索 begin -->
        <div class="advSeaBox">
          <div class="advTit">
            <b class="advGj">高级检索</b>
            <a class="Reback fr" @click="returnSimpleSearch" style="top: 2px;">返回</a>
          </div>
          <div class="bcRcon_top">
            <i :class="{cur:advanceCnkiType==item.key}"
               v-for="item in tabConfig"
               @click="advanceCnkiType=item.key">{{item.name}} </i>
            <div class="cnkimore" v-if="false">
              <span class="cnkgd">更多</span>
              <div class="cnkimoreHide">
                <ins class="ytjj"></ins>
                <span>教学教案</span>
                <span>多媒体教辅</span>
                <span>理化生实验室</span>
                <span>期刊（完中版）</span>
                <span>期刊（高中版）</span>
                <span>期刊（初中版）</span>
                <span>期刊（小学版）</span>
              </div>
            </div>
          </div>
          <div class="ordSeaBox clearfix">
            <!-- line -->
            <ul class="cnSeaLi" v-for="item,index in advanceConditions">
              <li class="cnkiS04" v-if="index==0">
                <ins class="cAddbtn" title="添加条件" @click="addAdvConditions"></ins>
                <ins class="cCutbtn" title="减少条件" @click="reduceAdvConditions"></ins>
              </li>
              <li class="cnkiS04" v-if="index!=0">
                <select name="" class="cnkiselectA" v-model="item.exstra">
                  <option value="AND">并且</option>
                  <option value="OR">或者</option>
                  <option value="NOT">不含</option>
                </select>
              </li>
              <li class="cnkiS01">
                <select name="" class="cnkiselectA" v-model="item.column">
                  <option v-bind:value="data.key" v-for="data in item.theme">{{data.name}}</option>
                </select>
              </li>
              <li class="cnkiS02">
                <input type="text" placeholder="输入检索词" class="cnkipitA" v-model.trim="item.searchKey"
                       @keyup.enter="advSearchButtonFn">
              </li>
              <li class="cnkiS05">
                <select name="" class="cnkiselectA" v-model="item.isAcurrate">
                  <option value="true">精确</option>
                  <option value="false">模糊</option>
                </select>
              </li>
            </ul>
            <!--<ul class="cnTjOther">-->
            <!--<li>-->
            <!--<label class="cnklab"> 时&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;间： </label>-->
            <!--<span><input placeholder="开始日" class="cnkidate" type="text"></span>-->
            <!--<em class="dataMar"> 到 </em>-->
            <!--<span><input placeholder="截止日" class="cnkidate" type="text"></span>-->
            <!--</li>-->
            <!--<li class="cnkiWxly">-->
            <!--<label class="cnklab">文献分类：</label> <input type="text" placeholder="输入检索词"-->
            <!--class="cnkipitA">-->
            <!--<ins class="wxlyBtn" title="选择文献分类"></ins>-->
            <!--</li>-->
            <!--</ul>-->
            <div class="advBotBTn">
              <a class="advBigBTn" @click="advSearchButtonFn">检索</a>
            </div>
          </div>
        </div>
        <!--  复杂检索 begin -->
      </div>
      <div class="cnkiSort" v-if="advanceData.length>0">
                <span class="fl" v-if="isAddBtn&&advanceResType!='Picture'">
                    <ins :class="{mcheck:advanceAlChecked,mchecked:!advanceAlChecked}"
                         @click="cnkiDataAllCheckFn(advanceData,'advance')"></ins>全选
                </span>
        <span class="tjbtn fl" style="margin-left: 10px;" @click="returnCnkiData(advanceData)"
              v-if="isAddBtn&&advanceResType!='Picture'">+ {{addBtnName}}</span>
        <span class="fr cnkitotal">共
                    <em class="orange">{{advanceTotal}}</em>条
                </span>
      </div>
      <div class="cnkibox">
        <div>
          <!-- line -->
          <dl class="cnkiList" v-for="data,index in advanceData">
            <dt class="blue">
                                <span class="checkbtn" v-if="isAddBtn&&advanceResType!='Picture'">
                                    <ins :class="{mcheck:data.isChecked,mchecked:!data.isChecked}"
                                         @click="cnkiDataCheckFn(data,advanceData,'advance')"></ins>
                                </span>
              <p v-html="(advancePageIndex-1)*advancePageSize+index+1+'.'+data.Title"
                 @click="toggleSummary(data,advanceData)"></p>
            </dt>
            <dd class="author">
              <p class="cnkitop">
                <span class="cnkiauthor" v-html="data.Creator"> </span>
                <span class="journal" v-html="data.Contributor"></span>
                <span class="nianqi" v-html="data.Year"></span>
                <span class="gray" v-html="data.Source"></span>
              </p>
            </dd>
            <dd class="cnkiSumary" v-show="data.SummaryShow">
              <p class="cnkitext" v-html="data.Summary"></p>
              <p class="sumbot">
                <span class="fbdate fl"> 发表时间：{{data.Year}}</span>
                <span class="fr">
                                    <a class="cnkiread" @click="readFullText(advanceResType,data,false)">阅读</a>
                                    <a class="cnkizwj" :href="data.LinkHref" target="_blank" v-if="advanceResType!=='Picture'"> 知网节</a>
                                </span>
              </p>
            </dd>
          </dl>
        </div>
        <div v-show="advanceTotal>advancePageSize&&!isAdvanceLoading" class="el-page-con">
          <el-pagination @current-change="advancePageHandle"
                         :current-page.sync="advancePageIndex"
                         :page-size="advancePageSize"
                         :pager-count="5"
                         layout=" pager, jumper"
                         :total="advanceTotal">
          </el-pagination>
        </div>

        <!-- 没有搜索时显示  begin -->
        <div class="cnkinodata" v-if="isAdvanceLoading">
          <p>正在检索请稍后.....</p>
        </div>
        <div class="cnkinodata" v-if="isAdvanceNull">
          <b class="orange">提示：</b>
          <p>没有符合条件的资源!</p>
        </div>
        <!-- 没有搜索时显示  end -->
      </div>
    </div>
    <!-- 复杂检索 end -->
    <!-- 资源在线阅读 -->
    <div class="fulltext" v-if="isFullText">
      <div class="fullName" :class="{'is-fullscreen': cnkiContent.type=='content'}">
        <h1 class="elips" v-html="cnkiContent.title"></h1>
        <button v-show="cnkiContent.type=='content' || cnkiContent.type == 'mp4'" class="fullread" @click="cnkiReadFullScreen">全屏阅读</button>
        <a class="Reback" @click="returnReadFullText">返回</a>
      </div>
      <!-- 全文阅读 -->
      <div class="fullcon cnki-read-online" v-show="cnkiContent.type=='content'" :style="{height: containerHeight + 'px'}">
        <iframe id="fullTextIframe" :src="cnkiContent.src" frameborder="0" class="iframe-read"
                @load="loadIframe"></iframe>
      </div>
      <!-- 图片 -->
      <div class="fullcon" v-show="cnkiContent.type=='picture'" :style="{height: containerHeight + 'px'}">
        <div class="cnkiSort" style="margin-bottom:10px;">
                    <span class="fl" v-if="isAddBtn&&fullTextImage.length>0">
                        <ins :class="{mcheck:imagesChecked,mchecked:!imagesChecked}" @click="imagesAllCheckFn"></ins>全选
                    </span>
          <span class="tjbtn fl" style="margin-left: 10px;" @click="returnfullTextImage"
                v-if="isAddBtn&&fullTextImage.length>0">+ {{addBtnName}}</span>
        </div>
        <p v-for="data in fullTextImage">
          <ins :class="{mcheck:data.isChecked,mchecked:!data.isChecked}"
               @click="imagesSingleCheckFn(data)"></ins>
          <img :src="data.Url" :alt="data.Name"/>
        </p>
      </div>
      <!--mp4-->
      <div class="fullcon cnki-read-online" v-show="cnkiContent.type=='mp4'" :style="{height: containerHeight + 'px', position: 'relative'}">
        <video :src="cnkiContent.videoSrc" controls="controls" class="video-center" autoplay="autoplay"></video>
      </div>
    </div>
  </div>
</template>

<script>
  import {Loading} from 'element-ui';
  import {mapActions, mapMutations} from 'vuex';
  import addTarget from '../../core/material';

  export default {
    data() {
      return {
        cnkiBaseurl: globalVar.cnkiFullTextAddr,
        cfed_url: globalVar.cfed_url,
        literature_url: globalVar.literature_url,
        picture_url: globalVar.picture_url,
        isSimpleSearch: true, //标识简单检索和复杂检索
        isAdvanceSearch: false,
        isFullText: false, //是否为全文阅读
        cnkiContent: {
          src: "",
          title: "",
          type: ""
        },
        fullTextImage: [],
        imagesChecked: false,
        imagesCheckedCount: 0,
        isSimpleReading: true,
        cnkiTypeList: [],
        simpleResType: "", //简单检索条件
        tabConfig: [],
        tabConfigTemp: [], // 知网资源基本搜索和高级搜索切换中保存基本搜索的选项数组1
        searchConfig: [],
        searchConfigTemp: [], // 知网资源基本搜索和高级搜索切换中保存基本搜索的选项数组2
        sortConfig: [],
        cnkiTheme: "",
        cnkiType: "",
        cnkiSorting: "",
        cnkikey: "",
        simplePageIndex: 1,
        simplePageSize: 6,
        simpleTotal: 0,
        simpleData: [],
        simpleCheckedCount: 0,
        simpleAlChecked: false,
        initFlag: true,
        isSimpleLoading: false,
        isSimpleNull: false,
        advanceResType: "", //高级检索条件
        advanceConditions: [],
        advanceCnkiType: "",
        advanceData: [],
        advancePageIndex: 1,
        advancePageSize: 6,
        advanceTotal: 0,
        advanceCheckedCount: 0,
        advanceAlChecked: false,
        isAdvanceLoading: false,
        isAdvanceNull: false,
        advanceSearchData: {}
      };
    },
    props: {
      courseCode: {
        type: String,
        default: ""
      },
      catalogCode: {
        type: String,
        default: ""
      },
      isAddBtn: {
        type: Boolean,
        default: true
      },
      addBtnName: {
        type: String,
        default: "添加"
      },
      containerHeight: {
        type: Number
      }
    },
    methods: {
      ...mapActions(['addStatistics']),
      ...mapMutations(['setReferenceInfo', ]),
      /**
       * iframe加载后，给messenger加载对象
       */
      loadIframe() {
        addTarget("fullTextIframe");
      },
      /**
       * 错误消息提示
       */
      showError({msg, type}){
        this.$message({
          showClose: true,
          message: msg,
          type: type || "error",
          duration: 2000
        });
      },
      //获取资源库
      getCnkiType() {
        axios.get(this.cnkiBaseurl + "/Api/Search/config")
          .then(res => {
            if (res && res.data && res.data.Code === 200) {
              this.simpleResType = res.data.Data[0].key;
              this.cnkiTypeList = res.data.Data;
            } else {
              this.showError({msg: "获取资源库信息失败!"});
            }
          })
          .catch(err => {
            console.log(err);
            this.showError({msg: "获取资源库信息失败!"});
          })
      },
      //获取资源库下的检索类型
      cnkiClassification(dataLib, flag) {
        axios.get(this.cnkiBaseurl + "/Api/Search/config/" + dataLib)
          .then(res => {
            if(res && res.data && res.data.Code === 200){
              this.tabConfig = res.data.Data.tabConfig || [];
              this.searchConfig = res.data.Data.searchConfig || [];
              this.sortConfig = res.data.Data.sortConfig || [];
              if (flag == "simple") {
                this.cnkiTheme =
                  this.searchConfig.length > 0
                    ? this.searchConfig[0].key
                    : "";
                this.cnkiType =
                  this.tabConfig.length > 0
                    ? this.tabConfig[0].key
                    : "";
                this.cnkiSorting =
                  this.sortConfig.length > 0
                    ? this.sortConfig[0].key
                    : "";
              }
              if (flag == "advance") {
                this.advanceCnkiType =
                  this.tabConfig.length > 0
                    ? this.tabConfig[0].key
                    : "";
                for (let item of this.advanceConditions) {
                  item.theme = JSON.parse(JSON.stringify(this.searchConfig));
                  item.column = this.searchConfig[0].key;
                }
              }
            } else {
              this.showError({msg: "获取初始化信息失败!"});
            }
          })
          .catch(err => {
            console.log(err);
            this.showError({msg: "获取初始化信息失败!"});
          })
      },
      //获取知网资源
      // noAddStsFlag 不参加统计传true 否则不用管
      cnkiDataRetrieve(pageIndex, noAddStsFlag) {
        let reg = /[<>]/;
        if(reg.test(this.cnkikey)){
          return this.showError({msg: "检索关键词不能包含<>", type: "warning"});
        }
        if(this.cnkikey.length==0){
          return this.showError({msg: "检索关键词不能为空", type: "warning"});
        }
        if(this.simplePageIndex !== pageIndex){
          return this.simplePageIndex = pageIndex;
        }
        this.initFlag = false;
        this.isSimpleNull = false;
        this.isSimpleLoading = true;
        this.simpleData.length = 0;
        this.simpleCheckedCount = 0;
        this.simpleAlChecked = false;
        let queryUrl = this.cnkiBaseurl + "/Api/search/query";
        if(process.env.NODE_ENV === "development"){// 开发阶段绕过限制
          queryUrl = "/corsWithHeader/Api/search/query";
        }
        axios.get(queryUrl, {
          params: {
            source: this.cnkiType,
            pageIndex: pageIndex,
            pageSize: this.simplePageSize,
            sortKey: this.cnkiSorting,
            key1: this.cnkiTheme +"|"+this.cnkikey+"|false"
          },
          headers: {'token': dataFromFather.token}
        }).then(res => {
          this.isSimpleLoading = false;
          if (!res || !res.data || res.data.Code !== 200) {
            this.showError({msg: "检索失败，请重试!"});
            return false;
          }
          var returnData = res.data.Data;
          this.simpleTotal = returnData.Count || 0;
          if (this.simpleTotal <= 0) {
            this.isSimpleNull = true;
            return false;
          }
          for(let i = 0; i < returnData.Rows.length; i++){
            returnData.Rows[i].SummaryShow = false;
            returnData.Rows[i].isChecked = false;
            returnData.Rows[i].LinkHref = returnData.Rows[i].Uri;
          }
          this.simpleData = returnData.Rows;
        }).catch(err => {
          console.log(err);
          this.showError({msg: "检索失败，请重试!"});
          this.isSimpleLoading = false;
        });
        // 统计埋点，查资料
        if(noAddStsFlag === true){
          return;
        }
        this.addStatistics(18);
      },
      formatAllData(rows) {
        var resultList = [];
        for (var i = 0; i < rows.length; i++) {
          var rowObj = {};
          rowObj.ID = rows[i].Id;
          for (var j = 0; j < rows[i].Cells.length; j++) {
            if (rows[i].Cells[j].Value != "") {
              rowObj[rows[i].Cells[j].Name] = rows[i].Cells[j].Value;
            }
          }
          rowObj.PhysicalTableName = rowObj.PhysicalTableName || "";
          if (this.isSimpleSearch) {
            if (this.simpleResType == "CVED") {
              rowObj.LinkHref = this.linkOfCVED(
                rowObj.ID,
                rowObj.PhysicalTableName,
                rowObj.FileName
              );
            } else if (this.simpleResType == "CFED") {
              rowObj.LinkHref =
                this.cfed_url +
                "?dbcode=" +
                rowObj.PhysicalTableName.substring(0, 4) +
                "&dbname=" +
                rowObj.PhysicalTableName +
                "&filename=" +
                rowObj.FileName;
            } else if (this.simpleResType == "Literature") {
              rowObj.LinkHref =
                this.literature_url +
                "?dbcode=" +
                rowObj.PhysicalTableName.substring(0, 4) +
                "&dbname=" +
                rowObj.PhysicalTableName +
                "&filename=" +
                rowObj.FileName;
            }
          }
          if (this.isAdvanceSearch) {
            if (this.advanceResType == "CVED") {
              rowObj.LinkHref = this.linkOfCVED(
                rowObj.ID,
                rowObj.PhysicalTableName,
                rowObj.FileName
              );
            } else if (this.advanceResType == "CFED") {
              rowObj.LinkHref =
                this.cfed_url +
                "?dbcode=" +
                rowObj.PhysicalTableName.substring(0, 4) +
                "&dbname=" +
                rowObj.PhysicalTableName +
                "&filename=" +
                rowObj.FileName;
            } else if (this.advanceResType == "Literature") {
              rowObj.LinkHref =
                this.literature_url +
                "?dbcode=" +
                rowObj.PhysicalTableName.substring(0, 4) +
                "&dbname=" +
                rowObj.PhysicalTableName +
                "&filename=" +
                rowObj.FileName;
            }
          }
          rowObj.SummaryShow = false;
          rowObj.isChecked = false;
          resultList.push(rowObj);
        }
        return resultList;
      },
      linkOfCVED(id, TableName, FileName) {
        var link = "";
        switch (this.cnkiType) {
          case "CVSD":
            link = "http://cved.cnki.net/Standard/Detail/" + id;
            break;
          case "CVBD":
            link = "http://r.cnki.net/knavi/ebook/Detail/CVBD/" + id;
            break;
          case "CVVD":
            link = "http://cved.cnki.net/video/Detail/" + id;
            break;
          case "CVKD":
            link = "http://cved.cnki.net/Course/Detail/" + id;
            break;
          case "CVCD":
            link = "http://cved.cnki.net/Matter/Detail/" + id;
            break;
          case "CVTD":
            link =
              this.cfed_url +
              "?dbcode=" +
              TableName.substring(0, 4) +
              "&dbname=" +
              TableName +
              "&filename=" +
              FileName;
            break;
          case "Picture":
            link = this.picture_url + id + ".html";
            break;
          default:
            break;
        }
        return link;
      },
      initCRFDData(data) {
        var list = [];
        for (var i = 0; i < data.length; i++) {
          list[i] = {};
          for (var j = 0; j < data[i].Cells.length; j++) {
            switch (data[i].Cells[j].Name) {
              case "Lemma":
                list[i].Title = data[i].Cells[j].Value;
                break;
              case "BookTitle":
                list[i].BookTitle = data[i].Cells[j].Value;
                break;
              case "FullTextSnapshot":
                list[i].Summary = data[i].Cells[j].Value;
                break;
              case "ItemCode":
                list[i].ItemCode = data[i].Cells[j].Value;
                break;
            }
            list[i].SummaryShow = false;
            list[i].LinkHref =
              "http://gongjushu.cnki.net/refbook/detail.aspx?db=crfd&RECID=" +
              list[i].ItemCode;
            list[i].isChecked = false;
          }
        }
        return list;
      },
      simplePageHandle(val) {
        // 在查询分页时，不参与统计
        // 第一页可以由别的条件触发，参与统计
        this.cnkiDataRetrieve(val, val != 1);
      },
      // 切换至高级检索
      advanceSearch() {
        this.isSimpleSearch = false;
        this.isAdvanceSearch = true;
        this.advanceResType = this.cnkiTypeList[0].key;
        this.tabConfigTemp = this.tabConfig; // 保存基本检索的选项数组1
        this.searchConfigTemp = this.searchConfig; // 保存基本检索的选项数组2
        this.advanceConditions = [
          {
            column: this.searchConfig[0].key,//检索主题
            searchKey: "",//关键词
            isAcurrate: true,//是否精确查询
            exstra: "",  //与或条件
            theme: JSON.parse(JSON.stringify(this.searchConfig))
          }];
      },
      //添加减少高级检索条件
      addAdvConditions() {
        var obj = {
          column: this.searchConfig[0].key,//检索主题
          searchKey: "",//关键词
          isAcurrate: true,//是否精确查询
          exstra: "AND",  //与或条件
          theme: JSON.parse(JSON.stringify(this.searchConfig))
        }
        this.advanceConditions.push(obj);
      },
      reduceAdvConditions() {
        if (this.advanceConditions.length == 1) {
          return;
        }
        this.advanceConditions.splice(this.advanceConditions.length - 1, 1);
      },
      //高级检索
      advSearchButtonFn() {
        let data = {
          source: this.advanceCnkiType,
          pageIndex: this.advancePageIndex,
          pageSize: this.advancePageSize,
          sortKey: "date"
        }
        let notAllowed = false;
        this.advanceConditions.forEach((val, index) => {
          let reg = /[<>]/;
          if (val.searchKey == "") {
            notAllowed = true;
            return this.showError({msg: "检索词不能为空!", type: "warning"});
          }
          if(reg.test(val.searchKey)){
            notAllowed = true;
            return this.showError({msg: "检索关键词不能包含<>", type: "warning"});
          }
          switch(index){
            case 0:data.key1=val.column+"|"+val.searchKey+"|"+val.isAcurrate;break;
            case 1:data.key2=val.exstra+"|"+val.column+"|"+val.searchKey+"|"+val.isAcurrate;break;
            case 2:data.key3=val.exstra+"|"+val.column+"|"+val.searchKey+"|"+val.isAcurrate;break;
            case 3:data.key4=val.exstra+"|"+val.column+"|"+val.searchKey+"|"+val.isAcurrate;break;
            case 4:data.key5=val.exstra+"|"+val.column+"|"+val.searchKey+"|"+val.isAcurrate;break;
          }
        })
        this.advanceSearchData = data;
        this.advCnkiDataChecked = false;
        this.advanceCheckedCount = 0;
        this.advanceAlChecked = false;
        if(notAllowed === false) {
          this.advSearchButtonAxios(1);
        }
      },
      // noAddStsFlag 不参加统计传true 否则不用管
      advSearchButtonAxios(pageIndex, noAddStsFlag) {
        if(this.advancePageIndex !== pageIndex){
          return this.advancePageIndex = pageIndex;
        }
        this.advanceData = [];
        this.isAdvanceLoading = true;
        this.isAdvanceNull = false;
        axios.get(this.cnkiBaseurl + "/Api/Search/query", {
          params: this.advanceSearchData,
          headers: {
            'token': dataFromFather.token
          }
        }).then(res => {
          if (res && res.data && res.data.Code === 200) {
            var returnData = res.data.Data;
            // 查询结果数量为0 或 查询结果中没有数量字段 都代表没有查询出来结果
            if (returnData.Count <= 0 || !returnData.Count) {
              this.advanceData = [];
              this.advanceTotal = 0;
              this.isAdvanceLoading = false;
              this.isAdvanceNull = true;
              return false;
            }
            if (pageIndex == 1 && returnData.Count > 0) {
              this.advanceTotal = returnData.Count;
            }
            for(let i = 0; i < returnData.Rows.length; i++){
              returnData.Rows[i].SummaryShow = false;
              returnData.Rows[i].isChecked = false;
              returnData.Rows[i].LinkHref = returnData.Rows[i].Uri;
            }
            this.advanceData = returnData.Rows;
            this.isAdvanceLoading = false;
          } else {
            this.showError({msg: "检索失败，请重试!"});
            this.isAdvanceLoading = false;
            this.isAdvanceNull = false;
          }
        }).catch(err => {
          console.log(err);
          this.showError({msg: "检索失败，请重试!"});
          this.isAdvanceLoading = false;
          this.isAdvanceNull = false;
        });
        if(noAddStsFlag == true) return;
        this.addStatistics(18);
      },
      advancePageHandle(val) {
        this.advSearchButtonAxios(val, val != 1);
      },
      returnSimpleSearch() {
        this.isAdvanceSearch = false;
        this.isSimpleSearch = true;
        this.advanceResType = "";
        this.tabConfig = this.tabConfigTemp; // 重置上次基本检索的选项数组1
        this.searchConfig = this.searchConfigTemp; // 重置上次基本检索的选项数组2
      },
      //数据选择
      cnkiDataAllCheckFn(arr, flag) {
        if (flag == "simple") {
          this.simpleAlChecked = !this.simpleAlChecked;
          this.simpleCheckedCount = 0;
        } else {
          this.advanceAlChecked = !this.advanceAlChecked;
          this.advanceCheckedCount = 0;
        }
        this.cnkiCheckedCount = 0;
        for (var i = 0; i < arr.length; i++) {
          if (flag == "simple") {
            arr[i].isChecked = this.simpleAlChecked;
            this.simpleCheckedCount = this.simpleAlChecked
              ? this.simpleCheckedCount + 1
              : this.simpleCheckedCount;
          }
          if (flag == "advance") {
            arr[i].isChecked = this.advanceAlChecked;
            this.advanceCheckedCount = this.simpleAlChecked
              ? this.advanceCheckedCount + 1
              : this.advanceCheckedCount;
          }
        }
      },
      cnkiDataCheckFn(item, arr, flag) {
        item.isChecked = !item.isChecked;
        if (flag == "simple") {
          this.simpleCheckedCount = item.isChecked
            ? this.simpleCheckedCount + 1
            : this.simpleCheckedCount - 1;
        }
        if (flag == "advance") {
          this.advanceCheckedCount = item.isChecked
            ? this.advanceCheckedCount + 1
            : this.advanceCheckedCount - 1;
        }
      },
      //图片全选
      imagesAllCheckFn() {
        this.imagesChecked = !this.imagesChecked;
        this.imagesCheckedCount = this.imagesChecked ? this.fullTextImage.length : 0;
        for (let item of this.fullTextImage) {
          item.isChecked = this.imagesChecked;
        }
      },
      imagesSingleCheckFn(item) {
        item.isChecked = !item.isChecked;
        this.imagesCheckedCount = item.isChecked ? this.imagesCheckedCount + 1 : this.imagesCheckedCount - 1;
      },
      //展示cnkiSummary
      toggleSummary(item, arr) {
        for (var i = 0; i < arr.length; i++) {
          arr[i].SummaryShow = false;
        }
        item.SummaryShow = !item.SummaryShow;
      },
      //全文阅读
      readFullText(type, item, flag) {
        if (type === "Literature" || type === "CFED" || type == "CVED") {
          this.cnkiContent.type = 'content';
          this.isSimpleReading = flag;
          this.isSimpleSearch = false;
          this.isAdvanceSearch = false;
          this.isFullText = true;
          let loadingInstance = Loading.service({fullscreen: true});
          this.cnkiContent.title = item.Title;
          this.cnkiContent.src = "";
          var dbCode = (item.TableName || "").substring(0, 4).toUpperCase();
          if(type == "CVED"){
            // 职教库
            this.readZJFullText(dbCode, item.FileName, item.PhysicalTableName, loadingInstance, item);
            return;
          }
          this.readFullTextAjax(dbCode, item.FileName, item.PhysicalTableName, loadingInstance, item);
        } else if (type === "Picture") {
          this.cnkiContent.type = 'picture';
          this.isSimpleReading = flag;
          this.isSimpleSearch = false;
          this.isAdvanceSearch = false;
          this.isFullText = true;
          let loadingInstance = Loading.service({fullscreen: true});
          this.cnkiContent.title = item.Title;
          this.cnkiContent.src = "";
          this.cnkiImages(item.Id, loadingInstance);
        } else if (type === "CFED1") {
          // 知好乐库
          if (!item.FileName) {
            this.showError({msg: "资源错误"});
          } else {
            let type = item.FileName.substring(item.FileName.lastIndexOf(".") + 1);
            switch (type.toUpperCase()) {
              case "SWF": // 资源是flash
                this.isSimpleReading = flag;
                this.isSimpleSearch = false;
                this.isAdvanceSearch = false;
                this.isFullText = true;
                this.cnkiContent.title = (item.Title || "").replace(/<span.*?>(.*?)<\/span>/g, "$1");
                this.cnkiContent.type = 'content';
                this.cnkiContent.src = item.LinkHref;
                break;
              case "MP4": // 资源是mp4格式
                this.isSimpleReading = flag;
                this.isSimpleSearch = false;
                this.isAdvanceSearch = false;
                this.isFullText = true;
                this.cnkiContent.title = (item.Title || "").replace(/<span.*?>(.*?)<\/span>/g, "$1");
                this.cnkiContent.type = 'mp4';
                this.cnkiContent.videoSrc = item.LinkHref;
                break;
              case "MP3": // 资源是MP3

              case "JPG": // 资源是图片
              case "JPEG":
              case "PNG":
              case "GIF":
              case "BMP":

              case "DOC":
              case "DOCX":
              case "XLS":
              case "XLSX":
              case "PPT":
              case "PPTX":
              case "TXT":
              case "PDF":
              case "CAJ":
                window.open(item.LinkHref, "_blank");
                break;
              default:
                this.showError({msg: '不支持的类型！'});
                break;
            }
          }
        } else {
          window.open(item.LinkHref, "_blank");
        }
        this.addStatistics(18); // 查看知网资源
      },
      // 职教资源在线查看
      readZJFullText(dbCode, fileName, tableName, loading, item){
        let queryUrl = this.cnkiBaseurl + "/help/cnki/vefulltext";
        // if(process.env.NODE_ENV == "development"){
        //     // queryUrl = "/ODataSearchV2/help/cnki/vefulltext";
        // }
        axios.get(this.cnkiBaseurl + "/help/cnki/vefulltext",{
          params: {
            dbCode: dbCode,
            fileName: fileName || "",
            tableName: tableName || "",
            userId: dataFromFather.userID,
            Id: item.Id,
            format: item.Format || ''
          }
        }).then(res => {
          if (res && res.data && res.data.Code === 200) {
            var num = Math.random(0, 5).toFixed(5);
            this.cnkiContent.src = res.data.Data ? res.data.Data + "&version=" + num : "";
          } else {
            this.showError({msg: "未找到碎片化数据！"});
          }
          loading.close();
        }).catch(err => {
          console.log(err);
          this.showError({msg: "未找到碎片化数据！"});
          loading.close();
        });
      },
      //获取图片
      cnkiImages(id, loading) {
        axios.get(this.cnkiBaseurl + "/help/image/uri/" + id)
          .then(res => {
            if (res && res.data && res.data.Code === 200) {
              for (let item of res.data.Data) {
                item.isChecked = false;
              }
              this.fullTextImage = res.data.Data;
            } else {
              this.showError({msg: "返回数据出错!"});
            }
            loading.close();
          })
          .catch(res => {
            console.log(res);
            this.showError({msg: "查看图片出错！"});
            loading.close();
          });
      },
      readFullTextAjax(dbCode, fileName, tableName, loading, item) {
        axios.get(this.cnkiBaseurl + "/help/cnki/fulltext",{
          params: {
            dbCode: dbCode,
            fileName: fileName || "",
            tableName: tableName || "",
            userId: dataFromFather.userID
          }
        }).then(res => {
          if (res && res.data && res.data.Code === 200) {
            var num = Math.random(0, 5).toFixed(5);
            let src = res.data.Data ? res.data.Data + "&version=" + num : "";
            this.cnkiContent.src = src;
            item.realdbCode = src.match(/dbCode=[^&]+/g)[0].split("=")[1];
            // 保存当前文献的信息，生成参考文献
            this.setReferenceInfo(item);
          } else {
            this.showError({msg: "未找到碎片化数据！"});
          }
          loading.close();
        }).catch(err => {
          console.log(err);
          this.showError({msg: "未找到碎片化数据！"});
          loading.close();
        });
      },
      //返回全文阅读
      returnReadFullText() {
        this.isFullText = false;
        this.isSimpleSearch = this.isSimpleReading;
        this.isAdvanceSearch = !this.isSimpleReading;
        this.cnkiContent.src = "";
        this.cnkiContent.videoSrc = "";
      },
      //添加后清空数据选择
      clearListChecked(arr) {
        for (let item of arr) {
          item.isChecked = false;
        }
      },
      //添加到课程
      // ZHL 知好乐
      returnCnkiData() {
        var data = [];
        let resourceType = "";
        // 简单检索
        if (this.isSimpleSearch) {
          resourceType = this.simpleResType === 'CFED1' ? "ZHL" : "";
          for (var i = 0; i < this.simpleData.length; i++) {
            var obj;
            if (this.simpleData[i].isChecked) { // 被选中的需要添加的内容
              if(resourceType === 'ZHL'){// 知好乐
                obj = JSON.parse(JSON.stringify(this.simpleData[i]));
              }else{// 其他
                obj = {
                  Id: this.simpleData[i].Id,
                  Title: this.simpleData[i].Title,
                  TableName: this.simpleData[i].TableName,
                  FileName: this.simpleData[i].FileName,
                  Creator: this.simpleData[i].Creator,
                  Source: this.simpleData[i].Source,
                  Summary: this.simpleData[i].Summary,
                  Date: this.simpleData[i].Date || "",
                  Href: this.simpleData[i].LinkHref,
                  Contributor: this.simpleData[i].Contributor,
                  Format: this.simpleData[i].Format, // 职教库需要
                  PhysicalTableName: this.simpleData[i].PhysicalTableName, // 职教库需要
                  resourceType: this.simpleData[i].ResourceType, // 职教库需要
                }
              }
              data.push(obj);
            }
          }
          this.simpleAlChecked = false;
          if (data.length <= 0) {
            this.$message({
              showClose: true,
              message: "没有选中要添加的资源！",
              type: "warning",
              duration: 2000
            });
            return false;
          } else {
            if(resourceType === 'ZHL'){
              this.$emit('add-ZHL-data', data);
            } else if(this.simpleResType === 'CVED'){
              // 职教库
              this.$emit("add-ZJ-data", data);
            } else{
              this.$emit("add-cnki-data", data);
            }
            this.clearListChecked(this.simpleData);
            this.addStatistics(19); // 知网资源添加
            return true;
          }
        }
        if (this.isAdvanceSearch) {
          resourceType = this.advanceResType === 'CFED1' ? "ZHL" : "";
          for (var i = 0; i < this.advanceData.length; i++) {
            var obj;
            if (this.advanceData[i].isChecked) {
              if(resourceType === 'ZHL'){// 知好乐
                obj = JSON.parse(JSON.stringify(this.advanceData[i]));
              }else{// 其他
                obj = {
                  Id: this.advanceData[i].Id,
                  Title: this.advanceData[i].Title,
                  TableName: this.advanceData[i].TableName,
                  FileName: this.advanceData[i].FileName,
                  Creator: this.advanceData[i].Creator,
                  Source: this.advanceData[i].Source,
                  Summary: this.advanceData[i].Summary,
                  Date: this.advanceData[i].Date,
                  Href: this.advanceData[i].LinkHref,
                  Format: this.simpleData[i].Format, // 职教库需要
                  PhysicalTableName: this.simpleData[i].PhysicalTableName, // 职教库需要
                  resourceType: this.simpleData[i].ResourceType, // 职教库需要
                }
              }
              data.push(obj);
            }
          }
          this.advanceAlChecked = false;
          if (data.length <= 0) {
            this.$message({
              showClose: true,
              message: "没有选中要添加的资源！",
              type: "warning",
              duration: 2000
            });
            return false;
          } else {
            if(resourceType === 'ZHL'){
              this.$emit('add-ZHL-data', data);
            } else if(this.advanceResType === 'CVED'){
              // 职教库
              this.$emit("add-ZJ-data", data);
            } else{
              this.$emit("add-cnki-data", data);
            }
            this.clearListChecked(this.advanceData);
            this.addStatistics(19); // 知网资源添加
            return true;
          }
        }
      },
      returnfullTextImage() {
        let data = []
        for (let item of this.fullTextImage) {
          let obj = {};
          if (item.isChecked) {
            obj.ID = item.ID;
            obj.Name = item.Name || item.ID;
            obj.Url = this.picture_url + item.ID + ".html";
            obj.Src = item.Url;
            data.push(obj);
          }
        }
        if (data.length <= 0) {
          this.$message({
            showClose: true,
            message: "没有选中要添加的图片！",
            type: "warning",
            duration: 2000
          });
          return false;
        } else {
          this.$emit("add-cnki-image", data);
          this.clearListChecked(this.fullTextImage);
          this.imagesChecked = false;
        }
        this.addStatistics(19); // 图片添加
      },
      // 全屏阅读
      cnkiReadFullScreen(){
        let that = this;
        const layer = layui.layer;
        let w = $(window).width();
        let h = $(window).height();
        if(this.cnkiContent.type === "mp4"){
          layer.open({
            type: 1,
            title: that.cnkiContent.title,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<video controls="controls" class="video-center" src="'+that.cnkiContent.videoSrc+'" autoplay="autoplay"></video>'
          });
        } else {
          layer.open({
            type: 2,
            title: that.cnkiContent.title,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: that.cnkiContent.src
          });
        }
      }
    },
    watch: {
      simpleResType(newVal, oldVal) {
        if (newVal == "") {
          return;
        }
        this.cnkiClassification(newVal, "simple");
      },
      cnkiType(newVal, oldVal) {
        if (this.cnkikey.length != 0) {
          this.cnkiDataRetrieve(1);
          return false;
        }
      },
      cnkiTheme(newVal, oldVal) {
        if (this.cnkikey.length != 0) {
          this.cnkiDataRetrieve(1);
        }
      },
      cnkiSorting(newVal, oldVal) {
        if (this.cnkikey.length != 0) {
          this.cnkiDataRetrieve(1);
        }
      },
      advanceResType(newVal, oldVal) {
        if (newVal == "") {
          return;
        }
        this.cnkiClassification(newVal, "advance");
      },
      simpleCheckedCount(newVal, oldVal) {
        this.simpleAlChecked = newVal > 0 && newVal == this.simpleData.length;
      },
      advanceCheckedCount(newVal, oldVal) {
        this.advanceAlChecked = newVal > 0 && newVal == this.advanceData.length;
      },
      imagesCheckedCount(newVal, oldVal) {
        this.imagesChecked = newVal > 0 && newVal == this.fullTextImage.length;
      }
    },
    created() {
      this.getCnkiType();
    }
  };
</script>

<style>
  .el-page-con {
    text-align: center;
  }
  .cnki-read-online {
    margin: 0;
    width: 100%;
    background-color: #fff;
    overflow: hidden;
  }
  .fullread {
    position: absolute;
    top: 7px;
    right: 60px;
    font-size: 12px;
    color: #00a4e6;
    padding: 0px 5px 0px 20px;
    border: 1px dashed #4acafe;
    border-radius: 2px;
    height: 20px;
    line-height: 20px;
    background: #fff url(../../../assets/images/fullread.png) no-repeat 5px 4px;
    cursor: pointer;
  }
  .fullread:hover{
    border:1px solid #4acafe;
    background-color: #dff9fd;
  }
  .is-fullscreen {
    padding-right: 136px;
  }
  .video-center {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
  }
</style>
